﻿using famails.bus;
using famails.common;
using famails.dto;
using FAMailUtils.MailGun;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class SenderVerify : System.Web.UI.Page
    {
        //private string accessKey = null;
        //private string secretKey = null;
        //private string password = null;
        //private string server = null;
        //private string username = null;

        //common.VerifyEmail veriryEmail = null;
        static log4net.ILog logs = log4net.LogManager.GetLogger("ErrorRollingLogFileAppender");
        static UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            userLogin = getUserLogin();
            if (!IsPostBack)
            {

                MailConfigBUS ctBUS = new MailConfigBUS();
                DataTable customerBySelect = ctBUS.GetByUserId(userLogin.UserId);
                if (customerBySelect != null)
                {
                    pnWarning.Visible = customerBySelect.Select("dnsVerified = 'Chưa đăng ký'").Length > 0;
                }
            }
        }



        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~/backend/page/login.aspx?rUrl=" + Request.Url.PathAndQuery);
            return null;
        }


        public DataTable CreateListEmail()
        {
            DataTable dt = new DataTable("ListEmail");
            DataColumn No = new DataColumn("No");
            DataColumn Status = new DataColumn("Status");
            DataColumn Name = new DataColumn("Name");
            DataColumn Email = new DataColumn("Email");
            DataColumn dnsVerified = new DataColumn("dnsVerified");
            DataColumn ID = new DataColumn("ID");
            DataColumn[] key = { No };
            dt.Columns.Add(No);
            dt.Columns.Add(Email);
            dt.Columns.Add(Status);
            dt.Columns.Add(Name); dt.Columns.Add(dnsVerified);
            dt.Columns.Add(ID);
            dt.PrimaryKey = key;
            return dt;
        }

        protected void btnVerify_Click(object sender, EventArgs e)
        {
            VerifyBUS vbs = new VerifyBUS();

            DomainUtils utils = new DomainUtils(ConfigurationManager.AppSettings["api-key"]);
            //try
            //{
            VerifyBUS vBus = new VerifyBUS();
            string err = ValidateNull();
            DataTable dt = vBus.GetByUserId(getUserLogin().UserId);
            int SenderCount = 0;
            int.TryParse(ConfigurationManager.AppSettings["SenderCount"] + "", out SenderCount);
            if (dt.Rows.Count >= SenderCount)
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Giới hạn tối đa cho phép xác thực là " + SenderCount + ". Vui lòng xóa email cũ !";
            }
            else if (!EmailTools.IsEmail(txtEmailVerify.Text))
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Email không đúng định dạng!";
            }
            else if (ConfigurationManager.AppSettings["domainBlock"].IndexOf(txtEmailVerify.Text.Split('@')[1]) >= 0)
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = "Domain nay không được phép sử dụng!";
            }
            else if (err == "")
            {
                // Get amazone config.
                //getConfigAmazone();
                //veriryEmail = new common.VerifyEmail(accessKey, secretKey);
                string email = txtEmailVerify.Text;
                DomainList list = utils.GetDomains();
                var result = list.items.Where(a => a.name == email.Split('@')[1] + "");
                bool status = false;
                if (result.Count() == 0)
                {
                    status = utils.AddDomain(email.Split('@')[1], @"");
                }
                List<string> urls = new List<string>();
                urls.Add(ConfigurationManager.AppSettings["click-tracking-url"]);
                urls.Add(ConfigurationManager.AppSettings["open-tracking-url"]);
                urls.Add(ConfigurationManager.AppSettings["delivery-tracking-url"]);
                urls.Add(ConfigurationManager.AppSettings["drop-tracking-url"]);
                Webhook.AddDomainTracking(ConfigurationManager.AppSettings["api-key"], urls, email.Split('@')[1]);
                //bool status = veriryEmail.VerifyEmailAddress(txtEmailVerify.Text.Trim());
                //if (status == true)
                //{
                // Them vao danh sach email xac thuc thanh cong.
                MailConfigBUS mcBUS = new MailConfigBUS();
                VerifyDTO vDto = new VerifyDTO();
                vDto.EmailVerify = txtEmailVerify.Text.Trim();
                vDto.isdelete = 0;
                vDto.userId = getUserLogin().UserId;
                DataTable T = vBus.CheckByEmail(vDto.EmailVerify, userLogin.UserId);
                if (T.Select("UserId=" + userLogin.UserId).Length > 0)
                {

                    pnSuccess.Visible = false;
                    pnError.Visible = true;

                    lblError.Text = "Email " + txtEmailVerify.Text + " đã được đăng ký";
                    return;
                }
                //if (vBus.CheckByEmail(vDto.EmailVerify).Rows.Count > 0)
                //{
                //    pnSuccessverify.Visible = true;
                //    pnError.Visible = false;
                //    lbverify.Text = "Email " + txtEmailVerify.Text + " này đã được verify trong hệ thống.Bạn vui lòng click vào để kích hoạt sử dụng ";
                //    return;
                //}
                else
                {


                    // Thêm vào cấu hình mail.
                    MailConfigDTO mcDTO = new MailConfigDTO();
                    mcDTO.DepartmentID = getUserLogin().DepartmentId;
                    mcDTO.userId = getUserLogin().UserId;
                    mcDTO.Email = txtEmailVerify.Text.Trim();
                    mcDTO.parentId = 1;
                    mcDTO.levelId = 1;
                    mcDTO.isSSL = true;
                    mcDTO.Port = 25;
                    //mcDTO.Server = server;
                    //mcDTO.username = username;
                    //mcDTO.Password = password;
                    mcDTO.Name = txtNameConfig.Text;

                    mcBUS.tblMailConfig_insert(mcDTO);

                    pnError.Visible = false;
                    lblSuccess.Text = "Bạn đã xác thực thành công email: " + txtEmailVerify.Text + "";
                    txtEmailVerify.Text = "";
                    txtNameConfig.Text = "";
                    pnSuccess.Visible = true;
                }
            }
            else
            {
                pnSuccess.Visible = false;
                pnError.Visible = true;
                lblError.Text = err;
                txtEmailVerify.Focus();
            }
        }

        private string ValidateNull()
        {
            string err = "";
            if (txtEmailVerify.Text == "")
            {
                err = "Bạn chưa nhập email!";
                return err;
            }
            else if (IsValidMail(txtEmailVerify.Text) == false)
            {
                err = "Bạn nhập không đúng định dạng Email!";
                return err;
            }
            else if (txtNameConfig.Text == "")
            {
                err = "Bạn chưa nhập tên cấu hình";
                return err;
            }
            return err;
        }
        protected bool checkExceedLimitEmail()
        {
            VerifyBUS vBus = new VerifyBUS();
            if (getUserLogin().DepartmentId != 1)
            {
                DataTable dt = vBus.GetByUserId(getUserLogin().UserId);
                if (dt.Rows.Count >= 2)
                {
                    return false;
                }
            }
            return true;
        }
        public bool IsValidMail(string emailaddress)
        {
            try
            {
                MailAddress m = new MailAddress(emailaddress);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }



        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void Delete(int id)
        {
            try
            {
                VerifyBUS vbs = new VerifyBUS();
                if (ConnectionData._MyConnection.State == ConnectionState.Closed)
                {
                    ConnectionData._MyConnection.Open();
                }

                string sql = "update tblMailConfig set Isdelete=1 where ID='" + id + "' and userid=" + userLogin.UserId;
                SqlCommand cmd = new SqlCommand(sql, ConnectionData._MyConnection);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                cmd.Dispose();


            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi trong quá trình xóa email</br>" + ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<MailConfigDTO> Search()
        {
            userLogin = (UserLoginDTO)HttpContext.Current.Session["us-login"];
            //string name = "", phone = "h", email = ""; int group = -1;
            MailConfigBUS ctBUS = new MailConfigBUS();
            DataTable customerBySelect = ctBUS.GetByUserId(userLogin.UserId);
            List<MailConfigDTO> result = new List<MailConfigDTO>();
            MailConfigDTO item = new MailConfigDTO();
            foreach (DataRow dr in customerBySelect.Rows)
            {
                item = new MailConfigDTO();
                item.Id = Convert.ToInt32(dr["Id"] + "");
                item.Email = dr["Email"] + "";
                item.Name = dr["Name"] + "";
                item.dnsVerified = dr["dnsVerified"] + "";
                item.status = dr["status"] + "";
                result.Add(item);
            }
            return result;
        }
    }

}